# -*- coding: utf-8 -*-
"""租赁合同管理系统 - 无窗口启动脚本"""

import sys
import os
import subprocess
import datetime
import time


def log_message(message, is_error=False):
    """记录日志信息"""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] {message}\n"
    log_file = "startup_error.log" if is_error else "startup.log"
    
    try:
        with open(log_file, "a", encoding="utf-8") as f:
            f.write(log_entry)
    except Exception as log_e:
        pass  # 静默处理日志写入失败


def show_error_box(message):
    """显示错误消息框"""
    try:
        import ctypes
        ctypes.windll.user32.MessageBoxW(0, message, "Error", 0)
    except Exception as msg_e:
        pass  # 静默处理消息框显示失败


if __name__ == "__main__":
    log_message("===== 应用启动尝试 =====")
    
    # 获取当前目录
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(current_dir)
        log_message(f"切换工作目录至: {current_dir}")
    except Exception as dir_e:
        error_msg = f"设置工作目录失败: {str(dir_e)}"
        log_message(error_msg, is_error=True)
        show_error_box(error_msg)
        sys.exit(1)
    
    # 主脚本路径
    main_script = os.path.join(current_dir, "main.py")
    
    # 检查主脚本是否存在
    if not os.path.exists(main_script):
        error_msg = f"未找到主脚本: {main_script}"
        log_message(error_msg, is_error=True)
        show_error_box(error_msg)
        sys.exit(1)
    
    log_message(f"主脚本位于: {main_script}")
    
    # 获取Python可执行文件路径
    python_exe = sys.executable
    log_message(f"当前Python可执行文件: {python_exe}")
    
    # 尝试使用pythonw.exe进行无窗口执行，如不可用则回退到python.exe
    exe_paths = []
    
    # 添加pythonw.exe到可执行文件列表
    pythonw_exe = os.path.join(os.path.dirname(python_exe), "pythonw.exe")
    if os.path.exists(pythonw_exe):
        exe_paths.append((pythonw_exe, "无窗口模式"))
        log_message(f"找到pythonw.exe: {pythonw_exe}")
    else:
        log_message(f"未找到pythonw.exe: {pythonw_exe}，将尝试python.exe")
    
    # 始终添加python.exe作为备用
    exe_paths.append((python_exe, "控制台模式"))
    
    # 尝试每个可执行文件直到成功
    success = False
    for exe_path, mode in exe_paths:
        try:
            log_message(f"尝试使用 {exe_path} 启动应用 ({mode})")
            
            # 设置创建标志以进一步隐藏窗口
            creationflags = 0
            if sys.platform.startswith('win'):
                creationflags = 0x08000000  # CREATE_NO_WINDOW
            
            # 启动进程
            process = subprocess.Popen(
                [exe_path, main_script],
                cwd=current_dir,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                creationflags=creationflags
            )
            
            # 给进程启动时间
            time.sleep(1)
            
            # 检查进程是否仍在运行
            if process.poll() is None:
                log_message(f"成功以 {mode} 启动应用")
                success = True
                break
            else:
                # 进程立即退出，获取错误输出
                stdout, stderr = process.communicate(timeout=5)
                error_msg = f"进程以代码 {process.returncode} 退出. stderr: {stderr.decode('utf-8', errors='replace')}"
                log_message(error_msg, is_error=True)
                
        except Exception as e:
            log_message(f"使用 {exe_path} 启动失败: {str(e)}", is_error=True)
    
    if success:
        log_message("应用启动成功完成")
    else:
        error_msg = "使用所有可用Python可执行文件启动应用失败"
        log_message(error_msg, is_error=True)
        show_error_box(error_msg)
        sys.exit(1)